const express = require("express");
const cors = require("cors")
const dbConn = require("./dbutils/dbutils.js")
const bodyparser = require("body-parser")
const app = express();
app.use(cors()) //允许跨域访问
app.use(bodyparser.urlencoded({
    extended: false
}))
app.get("/findAll", (request, response) => {
    const sql = "select * from tb_stu"
    dbConn.query(sql, (error, result) => {
        if (error) {
            response.json({ code: "100", message: "查询失败" });
            console.log("test" + error)
        } else {
            response.json({ code: "200", message: "查询成功", data: result });
        }
    })
})
app.get("/findByUname", (request, response) => {
    // response.setCharacterEncoding("UTF-8");
    if (!response.headersSent) {
        response.setHeader('Content-Type', 'text/plain');
        response.setHeader("Access-Control-Allow-Origin", "*");
    }
    const uname = request.query.uname
    let sql = "select * from tb_stu where uname=?"
    dbConn.query(sql, [uname], (error, result) => {
        if (error) {
            response.json({ code: "100", message: "查询失败", data: error });

        } else {
            console.log("test" + JSON.stringify(result))
            response.json({ code: "200", message: "查询成功", data: result });
        }
    })
})
app.post("/insert", (request, response) => {
    const params=request.query;
    let sql = "insert into tb_stu(uname,upwd) values(?,md5(?))"
    dbConn.query(sql, [params.uname, params.upwd], (error, result) => {
        if (error) {
            response.json({ code: "120", message: "插入失败", data: 0 });

        } else {
            console.log("test" + JSON.stringify(result))
            response.json({ code: "200", message: "插入成功", data: 1 });
        }
    })
})
// app.post("/update",(request,response)=>{

//     response.json();
// })
// app.post("/delete",(request,response)=>{

//     response.json();
// })
// app.get("/",(req,res)=>{
//    const params= req.query;
//     res.setHeader('Content-Type','text/javascript;charset=utf8') 
//     res.json({"code":200,result:[{id:100,title:params}]})
// })
// app.get("/findAll",(req,res)=>{
//     res.setHeader('Content-Type','text/javascript;charset=utf8') 
//     res.json({"code":200,result:[{id:100,title:"用户"}]})
// })
// app.post("/delete",(req,res)=>{
//     res.setHeader('Content-Type','text/javascript;charset=utf8') 
//     res.json({"code":200,result:[{id:100,title:"用户"}]})
// })

app.listen(3000, () => {
    console.log("服务器已经启动,访问地址：http://localhost:3000")
})